//
//  TRAppDelegate.m
//  WeiMiLan
//
//  Created by Mac on 14-7-16.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRAppDelegate.h"
#import "UIImage+Util.h"
#import "TRLeftViewController.h"
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

#import "TRNewGoodsViewController.h"
#import "TRSendWebViewController.h"
#import "NSUserDefaults+FirstLaunch.h"
#import "ToolKit.h"
#import "UMSocialWechatHandler.h"

@interface TRAppDelegate ()

@end


@implementation TRAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
   
    [UMSocialData setAppKey:@"55f91c24e0f55a31110057a2"];
    
    
    self.urlHearder = [[NSUserDefaults standardUserDefaults]objectForKey:@"urlHeader"];

    NSString * gifPath = [[NSBundle mainBundle] pathForResource:@"mao_loading" ofType:@"gif"];
    NSData * gifData = [NSData dataWithContentsOfFile:gifPath];
    self.gifImage = [[OLImage alloc]initWithData:gifData];

    [self initDDMenuController];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    self.userName=@"";
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleFade];
    NSLog(@"沙箱位置：%@",NSHomeDirectory());
    
    
    self.loadingImage = [UIImage imageNamed:@"nodata_public"];
    
    //向微信注册
    BOOL isok = [WXApi registerApp:@"wx726d9f7f8a68d8ce"];
    if (isok) {
        NSLog(@"注册微信成功");
    }else{
        NSLog(@"注册微信失败");
    }
    
    
     [UMSocialWechatHandler setWXAppId:@"wx726d9f7f8a68d8ce" appSecret:@"a4bccd8b02804a88275448966ba3881c" url:@"http://www.umeng.com/social"];
    
    [UMSocialQQHandler setQQWithAppId:@"1104790013" appKey:@"QZTalfLH29s7vD1F" url:@"http://www.umeng.com/social"];    
    
    
    [SMSSDK registerApp:@"a37c60f34756" withSecret:@"194c64013dd0daf1b806d3423720b679"];

    //  友盟的方法本身是异步执行，所以不需要再异步调用
    [MobClick startWithAppkey:UMENG_APPKEY];
    [UMFeedback setAppkey:UMENG_APPKEY];
    [self setupUMessage:launchOptions];
    [self setUMSocialDataSet];
    self.markString=@"";

    //友盟检测版本
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    [MobClick setAppVersion:version];
    [MobClick checkUpdate];
    [MobClick checkUpdate:@"新版本" cancelButtonTitle:@"忽略" otherButtonTitles:@"更新"];
    
    
    
    if ([QLPropertyUtils getBoolByKey:@"520" defaultValue:NO]==NO) {
        BOOL b = [QLPropertyUtils getBoolByKey:@"firstInstall" defaultValue:YES];
        if (b==NO) {
            [self performSelector:@selector(alertToAppstore) withObject:nil afterDelay:300];
        }
    }

    
    self.window.backgroundColor = [UIColor whiteColor];

    return YES;
}

- (void)alertToAppstore
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请给一个好评吧，每次都厚着脸皮要大家的好评，在这里表示歉意。有了大家的好评微私募就会得到更多用户的关注。当然如果有问题，你也可以联系我们。" delegate:self cancelButtonTitle:@"残忍拒绝" otherButtonTitles:@"支持一下",@"不好用！提意见", nil];
    alert.tag = 520;
    [alert show];
    
}

#pragma mark---初始化侧栏试图
-(void)initDDMenuController
{
    TRUserLoginViewController *loginVc = [[TRUserLoginViewController alloc] init];
    self.ddVC=[self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"ddVC"];
    self.rootVC=[self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"TRTabBarViewController"];
    self.leftVC=[self.window.rootViewController.storyboard instantiateViewControllerWithIdentifier:@"leftVC"];
    
    if([[QLUserManager shareInstance] getLastUserInfoFromNative]==nil)
    {
        self.ddVC.rootViewController = loginVc;
        [[NSUserDefaults standardUserDefaults] setFirstLaunch:NO];
    }else{
        self.ddVC.rootViewController = self.rootVC;
    }
  //  [self.ddVC addChildViewController:self.leftVC];
    self.ddVC.leftViewController=self.leftVC;
    self.window.rootViewController=self.ddVC;
}

- (void)appUpdate:(NSDictionary *)appInfo
{

}

#pragma mark ---友盟社会化分享
-(void)setUMSocialDataSet
{
    // [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ,UMShareToQzone,UMShareToWechatsession,UMShareToWechatTimeline]];
    
    //友盟社会化分享
   // [UMSocialData setAppKey:UMSocialAppKey_QiYe]; //企业
    //打开调试log的开关
    [UMSocialData openLog:NO];
    //如果你要支持不同的屏幕方向，需要这样设置，否则在iPhone只支持一个竖屏方向
    [UMSocialConfig setSupportedInterfaceOrientations:UIInterfaceOrientationMaskAll];
    //打开新浪微博的SSO开关
    [UMSocialSinaHandler openSSOWithRedirectURL:@"http://sns.whalecloud.com/sina2/callback"];
    //设置分享到QQ空间的应用Id，和分享url 链接
    [UMSocialQQHandler setQQWithAppId:QQWithAppId appKey:QQWithAppKey url:@"http://www.umeng.com/social"];
    //设置支持没有客户端情况下使用SSO授权
    [UMSocialQQHandler setSupportWebView:YES];
    //设置易信Appkey和分享url地址
  //  [UMSocialYixinHandler setYixinAppKey:YiXunWithAppId url:@"www.vsmu.cn"];
}

- (void)setupUMessage:(NSDictionary *)launchOptions
{
    //set AppKey and LaunchOptions
    [UMessage startWithAppkey:UMENG_APPKEY launchOptions:launchOptions];
    
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0"))
    {
        //register remoteNotification types （iOS 8.0及其以上版本）
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        //register remoteNotification types (iOS 8.0以下)
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
         |UIRemoteNotificationTypeSound
         |UIRemoteNotificationTypeAlert];
    }
#else
    
    //register remoteNotification types (iOS 8.0以下)
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge
     |UIRemoteNotificationTypeSound
     |UIRemoteNotificationTypeAlert];
    
#endif
    //for log
    [UMessage setLogEnabled:NO];
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"注册远程通知成功----%@", deviceToken);
    [UMessage registerDeviceToken:deviceToken];
    
   
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSLog(@"接收到远程通知--%@", userInfo);
    self.notificationInfo = userInfo;
    if (self.notificationInfo) {
        [self openNotification:self.notificationInfo];
    }
    
    NSString *messge = userInfo[@"aps"][@"alert"];
    
    NSString* date;
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"MM-dd hh:mm:ss"];
    
    date = [formatter stringFromDate:[NSDate date]];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"message"] = messge;
    dict[@"time"] = date;
    dict[@"messageID"] = userInfo[@"ID"];
    [self.messageArr addObject:dict];
    [self saveArray:self.messageArr];
    
    [UMessage didReceiveRemoteNotification:userInfo];
    
    
}
- (NSMutableArray *)messageArr {
    if (_messageArr == nil) {
        _messageArr = [self read];
        if (_messageArr == nil) {
            _messageArr = [NSMutableArray array];
        }
    }
    return _messageArr;
}
- (void)saveArray:(NSMutableArray *)data
{
    // 1.获得沙盒根路径
    NSString *home = NSHomeDirectory();
    
    // 2.document路径
    NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];

    NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
    
    [data writeToFile:filepath atomically:YES];
}

- (NSMutableArray *)read {
    // 1.获得沙盒根路径
    NSString *home = NSHomeDirectory();
    
    // 2.document路径
    NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
    
    // 3.文件路径
    NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
    
    // 4.读取数据
    NSMutableArray *data = [NSMutableArray arrayWithContentsOfFile:filepath];
    NSLog(@"%@", data);
    return data;
}
/**
 这里处理新浪微博SSO授权之后跳转回来，和微信分享完成之后跳转回来
 */
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    //return  [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil]||[WXApi handleOpenURL:url delegate:self];
//    if ([sourceApplication isEqualToString:@"com.tencent.xin"]) {
//        return  [WXApi handleOpenURL:url delegate:self];
//    }else{
//        return [UMSocialSnsService handleOpenURL:url wxApiDelegate:nil];
//    }
//}

#pragma mark web
-(WebAPI *)webAPI
{
    return [WebAPI defaultManager];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return  [UMSocialSnsService handleOpenURL:url];
}
//
//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
//{
//    return  [WXApi handleOpenURL:url delegate:self];
//}

-(void)cancelThread:(RCDraggableButton *)btn{
    UIAlertView * alter = [[UIAlertView alloc]initWithTitle:@"取消上传任务" message:@"是否取消当前未完成的任务" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alter show];
}

//上传图片
- (void)sendImageWithImage:(NSDictionary *)imageDict andName:(NSArray *)nameArr
{
    //开始上传
    NSLog(@"开始上传图片！");
    self.nameArr = nameArr;
    self.sendImagesDict=imageDict;
    
    self.byteCent =[@{}mutableCopy];
    self.numCount=1;
    self.imageCount =[imageDict[@"imageArray"] count];
    if (!_upDataLoadingBtn) {
        
        int loading_W = 60;
        int loading_H = 50;
        _upDataLoadingBtn = [[RCDraggableButton alloc]initInKeyWindowWithFrame:CGRectMake(kUI_SCREEN_WIDTH-loading_W, kUI_SCREEN_HEIGHT-loading_H*2, loading_W, loading_H)];
        
        //取消线程
        [_upDataLoadingBtn addTarget:self action:@selector(cancelThread:) forControlEvents:UIControlEventTouchUpInside];
        NSString * loading = [NSString stringWithFormat:@"上传中(0/%d)",(int)[imageDict[@"imageArray"] count]];
        [_upDataLoadingBtn setTitle:loading forState:UIControlStateNormal];
        [_upDataLoadingBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        _upDataLoadingBtn.titleLabel.font = [UIFont systemFontOfSize:11];
        OLImageView * iv = [[OLImageView alloc]initWithFrame:CGRectMake(0, loading_H-10, loading_W, 10)];
        iv.backgroundColor = [UIColor whiteColor];
        
        OLImage *o;
        NSString *str=[[NSBundle mainBundle] pathForResource:@"加载-046" ofType:@"gif"];
        NSData *data=[NSData dataWithContentsOfFile:str];
        o=[[OLImage alloc] initWithData:data];
        iv.image = o;
        
        
        [_upDataLoadingBtn addSubview:iv];
    }
    
    self.currentIndex = 0;
    [self completedUpload];
}

- (void)completedUpload
{
    NSNumber * countNum = [NSNumber numberWithInt:(int)self.imageCount];
    NSArray *imageArray = self.sendImagesDict[@"imageArray"];
    if (self.currentIndex<imageArray.count) {
        UIImage *image = self.sendImagesDict[@"imageArray"][self.currentIndex];
        self.uploadImage = image;//[self shrinkImage:image andName:self.nameArr[self.currentIndex]];
        [self sendImageToService:@{
                                   @"file.file":self.uploadImage,
                                   @"description":self.sendImagesDict[@"description"],
                                   @"productName":self.sendImagesDict[@"productName"],
                                   @"price":self.sendImagesDict[@"price"],
                                   @"pkgId":self.sendImagesDict[@"pkgId"],
                                   @"saleType":self.sendImagesDict[@"saleType"],
                                   @"imageArrayCount":countNum,
                                   @"createDate":self.sendImagesDict[@"createDate"]
                                   
                                   
                                   } andURLString:ApplicationDelegate.uploadUrl fileName:self.nameArr[self.currentIndex]];
    }else{
        NSNotification *notification = [NSNotification notificationWithName:@"UPLOAD_SUCCESS" object:@"success"];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
        [SVProgressHUD showSuccessWithStatus:@"图片上传成功！"];
        NSLog(@"上传成功");
        [_upDataLoadingBtn removeFromSuperview];
        [RCDraggableButton removeAllFromKeyWindow];
        self.upDataLoadingBtn=nil;
        self.sendImagesDict=nil;
    }
    self.currentIndex++;
}

- (UIImage*)shrinkImage:(UIImage*)image andName:(NSString*)name{
    float compressionVal = 1.0;
    float maxVal = 0.3;//MB
    
    UIImage *compressedImage = image; //get UIImage from imageView
    
    int iterations = 0;
    int totalIterations = 0;
    
    float initialCompressionVal = 0.00000000f;
    
    while (((((float)(UIImageJPEGRepresentation(compressedImage, compressionVal).length))/(1048576.000000000f)) > maxVal) && (totalIterations < 1024)) {
        
        NSLog(@"Image is %f MB", (float)(((float)(UIImageJPEGRepresentation(compressedImage, compressionVal)).length)/(1048576.000000f)));//converts bytes to MB
        
        compressionVal = (((compressionVal)+((compressionVal)*((float)(((float)maxVal)/((float)(((float)(UIImageJPEGRepresentation(compressedImage, compressionVal).length))/(1048576.000000000f)))))))/(2));
        compressionVal *= 0.97;//subtracts 3% of it's current value just incase above algorithm limits at just above MaxVal and while loop becomes infinite.
        
        if (initialCompressionVal == 0.00000000f) {
            initialCompressionVal = compressionVal;
        }
        
        iterations ++;
        
        if ((iterations >= 3) || (compressionVal < 0.1)) {
            iterations = 0;
            NSLog(@"%f", compressionVal);
            
            compressionVal = 1.0f;
            
            compressedImage = [UIImage imageWithData:UIImageJPEGRepresentation(compressedImage, compressionVal)];
            float resizeAmount = 1.0f;
            resizeAmount = (resizeAmount+initialCompressionVal)/(2);//percentage
            resizeAmount *= 0.97;//3% boost just incase image compression algorithm reaches a limit.
            resizeAmount = 1/(resizeAmount);//value
            initialCompressionVal = 0.00000000f;
            
            
            UIView *imageHolder = [[UIView alloc] initWithFrame:CGRectMake(0,0,(int)floorf((float)(compressedImage.size.width/(resizeAmount))), (int)floorf((float)(compressedImage.size.height/(resizeAmount))))];//round down to ensure frame isnt larger than image itself
            
            UIImageView *theResizedImage = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,(int)ceilf((float)(compressedImage.size.width/(resizeAmount))), (int)ceilf((float)(compressedImage.size.height/(resizeAmount))))];//round up to ensure image fits
            theResizedImage.image = compressedImage;
            
            
            [imageHolder addSubview:theResizedImage];
            
            
            UIGraphicsBeginImageContextWithOptions(CGSizeMake(imageHolder.frame.size.width, imageHolder.frame.size.height), YES, 1.0f);
            CGContextRef resize_context = UIGraphicsGetCurrentContext();
            [imageHolder.layer renderInContext:resize_context];
            compressedImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            
            
            //after 3 compressions, if we still haven't shrunk down to maxVal size, apply the maximum compression we can, then resize the image (90%?), then re-start the process, this time compressing the compressed version of the image we were checking.
            
            NSLog(@"resize");
        }
        
        totalIterations ++;
        
    }
    
    if (totalIterations >= 1024) {
        NSLog(@"Image was too big, gave up on trying to re-size");//too many iterations failsafe. Gave up on trying to resize.
    } else {
        if ([name hasSuffix:@".jpg"]||[name hasSuffix:@".JPG"]) {
            NSData *imageData = UIImageJPEGRepresentation(compressedImage, compressionVal);
            NSLog(@"FINAL Image is %f MB ... iterations: %i", (float)(((float)imageData.length)/(1048576.000000f)), totalIterations);//converts bytes to MB
            image = [UIImage imageWithData:imageData];//save new image to UIImageView.
        }else{
            NSData *imageData = UIImagePNGRepresentation(compressedImage);
            NSLog(@"FINAL Image is %f MB ... iterations: %i", (float)(((float)imageData.length)/(1048576.000000f)), totalIterations);//converts bytes to MB
            image = [UIImage imageWithData:imageData];//save new image to UIImageView.
        }
    }
    
    return image;
}
-(void)sendMessageToService:(NSString *)message URLString:(NSURL*)url{
    NSLog(@"URL:%@",url);
//    NSData *bodyData = [[message stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]dataUsingEncoding:NSUTF8StringEncoding];//把bodyString转换为NSData数据
//
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
//                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
//                                                       timeoutInterval:10];//请求这个地址， timeoutInterval:10 设置为10s超时：请求时间超过10s会被认为连接不上，连接超时
//    
//    [request setHTTPMethod:@"POST"];//POST请求
//    [request setHTTPBody:bodyData];//body 数据
//    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type:text"];//请求头
//    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];//同步发送request，成功后会得到服务器返回的数据
//    //返回的数据 根据系统的不同会返回不同编码的数据，比如windows 为GBK，Ubuntu 为UTF8.。。
//    //注意转换编码格式
//    if (!_manager) {
//        _manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
//    }
//    AFHTTPResponseSerializer *serializer = _manager.responseSerializer;
//    NSMutableSet *set = [NSMutableSet setWithObjects:@"text/html", nil];
//    [set unionSet:serializer.acceptableContentTypes];
//    serializer.acceptableContentTypes = set;
//    
//    NSURLSessionDataTask *task = [_manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
//        
//    }];
//    [task resume];
    NSLog(@"URL:%@",url);
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    NSData *data = [[message stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"数据大小:%f",(unsigned long)data.length/(1048576.000000f));
    
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];

            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; description=\"%@\"\r\n\r\n",message];
            //添加字段的值
            [body appendFormat:@"%@\r\n",message];

    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    //[body appendFormat:@"Content-Disposition: form-data; name=\"file.file\"; filename=\"file.file.png\"\r\n"];
    [body appendFormat:@"Content-Disposition: form-data; name=\"file.file\";description=\"%@\"; filename=\filename\"\r\n",message];

        [body appendFormat:@"Content-Type: text\r\n\r\n"];

    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    if (!_manager) {
        _manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    }
    AFHTTPResponseSerializer *serializer = _manager.responseSerializer;
    NSMutableSet *set = [NSMutableSet setWithObjects:@"text/html", nil];
    [set unionSet:serializer.acceptableContentTypes];
    serializer.acceptableContentTypes = set;
    
    NSURLSessionDataTask *task = [_manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        
        if (error) {
            NSLog(@"任务%d上传失败1：%@",(int)task.taskIdentifier,error);
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"第%d张上传失败",(int)self.numCount]];
            NSString * loading = [NSString stringWithFormat:@"上传中(%d/%d)",(int)self.numCount,(int)self.imageCount];
            [_upDataLoadingBtn setTitle:loading forState:UIControlStateNormal];
            self.numCount++;
        } else {
//            if ([responseObject[@"code"] isEqualToString:@"0000"]) {
//                
//                NSString * message = [NSString stringWithFormat:@"第%d张图片上传成功",(int)self.numCount];
//                NSString * loading = [NSString stringWithFormat:@"上传中(%d/%d)",(int)self.numCount,(int)self.imageCount];
//                [_upDataLoadingBtn setTitle:loading forState:UIControlStateNormal];
//                NSLog(@"任务%d成功：%@",(int)task.taskIdentifier,message);
//                
//                self.numCount++;
//            }else{
//                NSLog(@"任务%d上传失败2",(int)task.taskIdentifier);
//                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"第%d张上传失败",(int)self.numCount]];
//                NSString * loading = [NSString stringWithFormat:@"上传中(%d/%d)",(int)self.numCount,(int)self.imageCount];
//                [_upDataLoadingBtn setTitle:loading forState:UIControlStateNormal];
//                self.numCount++;
//            }
        }
//        [self completedUpload];
    }];
//    NSLog(@"上传任务%d",(int)task.taskIdentifier);
//    [self.byteCent setObject:[NSNumber numberWithInt:(int)data.length] forKey:[NSString stringWithFormat:@"任务%d",(int)task.taskIdentifier]];
    [task resume];

}
-(void)sendImageToService:(NSDictionary*)params andURLString:(NSURL*)url fileName:(NSString *)fileName{
    NSLog(@"URL:%@",url);
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    UIImage *image=[params objectForKey:@"file.file"];
    //得到图片的data
    NSData* data;
    data = UIImageJPEGRepresentation(image,1.0);
    NSLog(@"数据大小:%f",(unsigned long)data.length/(1048576.000000f));
    
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [params allKeys];
    
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        if(![key isEqualToString:@"file.file"])
        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[params objectForKey:key]];
        }
    }
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    //[body appendFormat:@"Content-Disposition: form-data; name=\"file.file\"; filename=\"file.file.png\"\r\n"];
    [body appendFormat:@"Content-Disposition: form-data; name=\"file.file\"; filename=\"%@\"\r\n",fileName];
    if ([fileName hasSuffix:@".jpg"]||[fileName hasSuffix:@".JPG"]){
        [body appendFormat:@"Content-Type: image/jpeg\r\n\r\n"];
    }else{
        [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    }
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    if (!_manager) {
        _manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    }
    AFHTTPResponseSerializer *serializer = _manager.responseSerializer;
    NSMutableSet *set = [NSMutableSet setWithObjects:@"text/html", nil];
    [set unionSet:serializer.acceptableContentTypes];
    serializer.acceptableContentTypes = set;
    
    NSURLSessionDataTask *task = [_manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        
        if (error) {
            NSLog(@"任务%d上传失败1：%@",(int)task.taskIdentifier,error);
            
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"第%d张上传失败",(int)self.numCount]];
            NSString * loading = [NSString stringWithFormat:@"上传中(%d/%d)",(int)self.numCount,(int)self.imageCount];
            [_upDataLoadingBtn setTitle:loading forState:UIControlStateNormal];
            self.numCount++;
        } else {
            if ([responseObject[@"code"] isEqualToString:@"0000"]) {
                
                NSString * message = [NSString stringWithFormat:@"第%d张图片上传成功",(int)self.numCount];
                NSString * loading = [NSString stringWithFormat:@"上传中(%d/%d)",(int)self.numCount,(int)self.imageCount];
                [_upDataLoadingBtn setTitle:loading forState:UIControlStateNormal];
                NSLog(@"任务%d成功：%@",(int)task.taskIdentifier,message);
                
                self.numCount++;
            }else{
                NSLog(@"任务%d上传失败2",(int)task.taskIdentifier);
                [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"第%d张上传失败",(int)self.numCount]];
                NSString * loading = [NSString stringWithFormat:@"上传中(%d/%d)",(int)self.numCount,(int)self.imageCount];
                [_upDataLoadingBtn setTitle:loading forState:UIControlStateNormal];
                self.numCount++;
            }
        }
        [self completedUpload];
    }];
    NSLog(@"上传任务%d",(int)task.taskIdentifier);
    [self.byteCent setObject:[NSNumber numberWithInt:(int)data.length] forKey:[NSString stringWithFormat:@"任务%d",(int)task.taskIdentifier]];
    [task resume];
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    NSURLSessionDataTask * task = object;
    
    NSString * key = [NSString stringWithFormat:@"任务%d",(int)task.taskIdentifier];
    CGFloat percent = task.countOfBytesSent/(CGFloat)[self.byteCent[key] intValue];
    
    CFLocaleRef currentLocale = CFLocaleCopyCurrent();
    
    CFNumberFormatterRef numberFormatter = CFNumberFormatterCreate(NULL, currentLocale, kCFNumberFormatterPercentStyle);
    
    CFNumberRef number = CFNumberCreate(NULL, kCFNumberFloatType, &percent);
    
    CFStringRef numberString = CFNumberFormatterCreateStringWithNumber(NULL, numberFormatter, number);
    NSLog(@"任务%d完成:%lld,%@",(int)task.taskIdentifier,task.countOfBytesSent,numberString);
    self.percentString = [NSString stringWithFormat:@"任务%d完成:%lld,%@",(int)task.taskIdentifier,task.countOfBytesSent,numberString];
}


#pragma mark=-------微信登陆
-(void)sendAuthRequest
{
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"123" ;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}

#pragma mark 分享给好友

- (id)init{
    if(self = [super init]){
        _scene = WXSceneTimeline;
    }
    return self;
}

-(void) changeScene:(NSInteger)scene
{
    _scene = (int)scene;
}

- (void) sendLinkContent
{
    if ([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi])
    {
        WXMediaMessage *message = [WXMediaMessage message];
        message.title = self.shareTitle;
        message.description =self.shareContent;
        if (ApplicationDelegate.shareImage) {
            UIImage * thumbImage = [UIImage scaleToSize:CGSizeMake(100, 100) for:ApplicationDelegate.shareImage];
            [message setThumbImage:thumbImage];
        }
        
        WXWebpageObject *ext = [WXWebpageObject object];
        ext.webpageUrl = self.shareURL;
        
        message.mediaObject = ext;
        
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = _scene;
        [WXApi sendReq:req];
    } else {
        
        [SVProgressHUD showErrorWithStatus:@"你还没用安装微信"];
    }
}
- (void)sendFileContent
{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = @"ML.png";
    message.description = @"Pro CoreData";
    [message setThumbImage:[UIImage imageNamed:@"1"]];
    UIImage * image = [UIImage imageNamed:@"1"];
    WXFileObject *ext = [WXFileObject object];
    ext.fileExtension = @"pdf";
    
    NSData *data;
    if (UIImagePNGRepresentation(image) == nil) {
        
        data = UIImageJPEGRepresentation(image, 1);
        
    } else {
        
        data = UIImagePNGRepresentation(image);
    }
    ext.fileData = data;
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = _scene;
    
    [WXApi sendReq:req];
}

- (void) sendImageContent:(UIImage *)image andImageDescription:(NSString*)description
{
    WXMediaMessage *message = [WXMediaMessage message];
    
    UIImage * thumbImage = [UIImage scaleToSize:CGSizeMake(100, 60) for:image];
    //32k
    NSData *imageData = UIImageJPEGRepresentation(thumbImage, 1);
    //大小控制
    float m = 0.01;
    float n = 1.0;
    while ((unsigned long)imageData.length>1024*20) {
        n = n - m;
        imageData = UIImageJPEGRepresentation(image,n);
        NSLog(@"数据大小：%lu",(unsigned long)imageData.length);
    }
    NSLog(@"数据最终大小：%lu",(unsigned long)imageData.length);
    [message setThumbImage:[UIImage imageWithData:imageData]];
    
    WXImageObject *ext = [WXImageObject object];
    
    ext.imageData = UIImagePNGRepresentation(image);
    NSLog(@"发送图片大小：%lu",(unsigned long)ext.imageData.length);
    if (ext.imageData.length>1024*1024*10) {
        //超出10M
        NSLog(@"发送图片大小超出10M");
        [MMProgressHUD showWithTitle:@"" status:@"大小超出10M,启动压缩"];
        float m = 0.01;
        float n = 1.0;
        
        imageData = ext.imageData;
        
        while ((unsigned long)imageData.length>1024*30) {
            n = n - m;
            imageData = UIImageJPEGRepresentation(image,n);
            NSLog(@"数据大小：%lu",(unsigned long)imageData.length);
        }
        NSLog(@"数据最终大小：%lu",(unsigned long)imageData.length);
        ext.imageData = imageData;
        [MMProgressHUD dismissWithSuccess:@"压缩成功，准备跳转"];
        
    }
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.text = description;
    req.message = message;
    req.scene = _scene;
    
    UIPasteboard *pasteboard = [UIPasteboard pasteboardWithName:UIPasteboardNameGeneral create:YES];
    
    pasteboard.string=@"复制文字";
    
    [WXApi sendReq:req];
    
}

- (void) sendImageContent:(UIImage *)image
{
    WXMediaMessage *message = [WXMediaMessage message];
    
    message.title=[NSString stringWithFormat:@"%@.png",[CurrentDate getCurrentDateString]];
    UIImage * thumbImage = [UIImage scaleToSize:CGSizeMake(100, image.size.height/(CGFloat)image.size.width*100) for:image];
    //32k
    NSData *imageData = UIImageJPEGRepresentation(thumbImage, 0.3);
    //大小控制
    float m = 0.1;
    float n = 1.0;
    while ((unsigned long)imageData.length>1024*20) {
        n = n * m;
        
        int jjj=(int)imageData.length;
        imageData = UIImageJPEGRepresentation(image,n);
        if (jjj==imageData.length) {
            break;
        }
        
        
        NSLog(@"数据大小：%lu",(unsigned long)imageData.length);
    }
    NSLog(@"ThumbImage数据最终大小：%lu",(unsigned long)imageData.length);
    [message setThumbImage:[UIImage imageWithData:imageData]];
    
    WXImageObject *ext = [WXImageObject object];
    
    ext.imageData = UIImagePNGRepresentation(image);
    
    NSLog(@"前：发送图片大小：%lu",(unsigned long)ext.imageData.length);
    if (ext.imageData.length>1024*1024*10) {
        //超出10M
        NSLog(@"发送图片大小超出10M");
        [MMProgressHUD showWithTitle:@"" status:@"大小超出10M,启动压缩"];
        
    }
    m = 0.1;
    n = 1.0;
    
    imageData = ext.imageData;
    
    while ((unsigned long)imageData.length>1024*512) {
        n = n * m;
        
        int sss = (int)imageData.length;
        imageData = UIImageJPEGRepresentation(image,n);
        NSLog(@"数据大小：%lu",(unsigned long)imageData.length);
        
        if (sss>=imageData.length) {
            break;
        }
    }
    NSLog(@"后：数据最终大小：%lu",(unsigned long)imageData.length);
    
    ext.imageData = imageData;
    
    [MMProgressHUD dismissWithSuccess:@"压缩成功，准备跳转"];
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.text = ApplicationDelegate.shareContent;
    req.message = message;
    req.scene = _scene;
    
    
    UIPasteboard *pasteboard = [UIPasteboard pasteboardWithName:UIPasteboardNameGeneral create:YES];
    
    pasteboard.string=@"复制文字";
    
    [WXApi sendReq:req];
    
}

- (void)sendGifContent:(NSArray *)array andFilePath:(NSString *)filePath
{
    WXMediaMessage *message = [WXMediaMessage message];
    //    [message setThumbImage:[UIImage imageNamed:@"res6thumb.png"]];
    ;
    
    UIImage * image =array[0];
    //32k
    NSData *imageData = UIImageJPEGRepresentation(image, 1);
    //大小控制
    float m = 0.1;
    float n = 1.0;
    while ((unsigned long)imageData.length>1024*20) {
        n = n - m;
        imageData = UIImageJPEGRepresentation(image,n);
        NSLog(@"数据大小：%lu",(unsigned long)imageData.length);
    }
    NSLog(@"数据最终大小：%lu",(unsigned long)imageData.length);
    [message setThumbImage:[UIImage imageWithData:imageData]];
    
    
    WXEmoticonObject *ext = [WXEmoticonObject object];
    
    ext.emoticonData = [NSData dataWithContentsOfFile:filePath] ;
    NSLog(@"大小是：%lu",(unsigned long)ext.emoticonData.length);
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = _scene;
    
    [WXApi sendReq:req];
}

- (void)getAccessToken:(NSString *)code
{
    NSString *getAccessTokenUrl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", @"wxac9fb2a70f90692a", @"7d0a92498ea65bae3d8fcf1bd8084db8",code];
    
    self.request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:getAccessTokenUrl]];
    
    __weak TRAppDelegate *weakSelf = self;
    __weak ASIHTTPRequest *weakRequest = self.request;
    
    [self.request setCompletionBlock:^{
        NSError *error = nil;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[weakRequest responseData]
                                                             options:kNilOptions
                                                               error:&error];
        if (error) {
            return;
        } else {
            NSLog(@"--- %@", [weakRequest responseString]);
        }
        
        NSString *accessToken = dict[@"access_token"];
        if (accessToken) {
            NSLog(@"--- AccessToken: %@", accessToken);
            
            __strong TRAppDelegate *strongSelf = weakSelf;
            [strongSelf getPrepayId:accessToken];
        }else{
            
        }
    }];
    
    [self.request setFailedBlock:^{
    }];
    [self.request startAsynchronous];
}

- (void)getPrepayId:(NSString *)accessToken
{
    NSString *getPrepayIdUrl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@", accessToken,@"ov-AHt85R6w_PP4LgGiPnZTOk8B8"];
    
    self.request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:getPrepayIdUrl]];
    __weak TRAppDelegate *weakSelf = self;
    __weak ASIHTTPRequest *weakRequest = self.request;
    
    [self.request setCompletionBlock:^{
        NSError *error = nil;
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[weakRequest responseData]
                                                             options:kNilOptions
                                                               error:&error];
        
        if (error) {
            
            return;
        } else {
            NSLog(@"--- %@", [weakRequest responseString]);
        }
        
        NSDictionary *dicts = dict;
        NSString *loginName = [dicts valueForKey:@"unionid"];
        NSString *nickname = [dicts ql_stringForKey:@"nickname"];
        NSString *headerUrl = [dicts ql_stringForKey:@"headimgurl"];
        [ToolKit saveUser:[dicts valueForKey:@"nickname"] userid:[dicts valueForKey:@"unionid"]];
        __strong TRAppDelegate *strongSelf = weakSelf;
        [strongSelf WXLogin:loginName nickname:nickname headerUrl:headerUrl];
        
    }];
    [self.request setFailedBlock:^{
        
    }];
    [self.request startAsynchronous];
}

- (void)WXLogin:(NSString *)loginName nickname:(NSString*)nickname headerUrl:(NSString*)headerUrl
{
    NSString *getPrepayIdUrl = @"http://ping.vsmu.cn/app/third-party-login?device=1";
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic ql_setObject:getPrepayIdUrl forKey:@"s"];
    [dic ql_setObject:loginName forKey:@"loginName"];
    [dic ql_setObject:nickname forKey:@"nickname"];
    [dic ql_setObject:headerUrl forKey:@"headerUrl"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"WXLogin" object:self userInfo:dic];
}

//#parm
#pragma mark 分享app到微信
- (void) sendAppLinkContent
{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = share_AppTitle;
    message.description = share_AppContent;
    [message setThumbImage:shre_AppImage];
    
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = share_AppURL;
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = _scene;
    
    [WXApi sendReq:req];
}

-(void) RespAppLinkContent
{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = share_AppTitle;
    message.description = share_AppContent;
    [message setThumbImage:shre_AppImage];
    
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = share_AppURL;
    
    message.mediaObject = ext;
    
    GetMessageFromWXResp* resp = [[GetMessageFromWXResp alloc] init];
    resp.message = message;
    resp.bText = NO;
    
    [WXApi sendResp:resp];
}

- (void)showMessage:(NSDictionary*)messageInfo
{
    if (self.messageView==nil) {
        self.messageView = [[[NSBundle mainBundle] loadNibNamed:@"QLMessageView" owner:self options:nil] lastObject];
    }
    int sw = self.window.frame.size.width;
    int sh = self.window.frame.size.height;
    CGRect r = CGRectMake((
                           sw-self.messageView.frame.size.width)/2,
                          sh-self.messageView.frame.size.height-self.messageView.frame.size.height+55,
                          self.messageView.frame.size.width,
                          self.messageView.frame.size.height);
    self.messageView.frame = r;
    self.messageView.alpha = 0.0;
    
    [self.window addSubview:self.messageView];
    self.messageView.messageInfo = messageInfo;
    
    [UIView animateWithDuration:0.4f animations:^{
        self.messageView.alpha = 1.0;
        CGRect r = CGRectMake((
                               sw-self.messageView.frame.size.width)/2,
                              sh-self.messageView.frame.size.height-self.messageView.frame.size.height,
                              self.messageView.frame.size.width,
                              self.messageView.frame.size.height);
        self.messageView.frame = r;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)openNotification:(NSDictionary*)dic
{
    if ([dic ql_hasObjectForKey:@"ID"]) {
        self.notificationInfo = dic;
        UIAlertView *alert = [[UIAlertView alloc] init];
        [alert setTitle:@"消息"];
        [alert setMessage:dic[@"aps"][@"alert"]];
        [alert addButtonWithTitle:@"确定"];
        [alert addButtonWithTitle:@"忽略"];
        alert.tag=2;
        alert.delegate = self;
        [alert show];
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==2) {
        if (buttonIndex==0) {
            TRProductDetailViewController *vc = [[TRProductDetailViewController alloc] init];
            vc.productTypeId = self.notificationInfo[@"ID"];
            [[QLPublic getCurrentRootViewController] presentViewController:vc animated:YES completion:nil];
        }
        return;
    }else if(alertView.tag==520){
        if (buttonIndex==1) {
            [QLPropertyUtils putBoolByKey:@"520" value:YES];
            NSString *str = @"https://itunes.apple.com/app/id1054652875";
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
        }else if (buttonIndex==2){
            self.feedbackViewController = [UMFeedback feedbackViewController];
            
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:self.feedbackViewController];
            nav.navigationBar.barStyle = UIBarStyleBlack;
            [[UIApplication
              sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
            // 设置左边的按钮
            UIBarButtonItem *returnButton = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(returnWeimilan)];
            [self.rootVC presentViewController:nav animated:YES completion:nil];
            
            self.feedbackViewController.navigationItem.leftBarButtonItem = returnButton;
        }
    }
    if (buttonIndex==1) {
        //取消上传
        if (_taskArr&&_taskArr.count>0) {
            [_taskArr makeObjectsPerformSelector:@selector(cancel)];
            
        }
        [_upDataLoadingBtn removeFromSuperview];
        [RCDraggableButton removeAllFromKeyWindow];
        self.upDataLoadingBtn=nil;
    }
}

- (void)returnWeimilan
{
    [[UIApplication
      sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self.feedbackViewController dismissViewControllerAnimated:YES completion:nil];
}

-(void) onReq:(BaseReq*)req
{
    if([req isKindOfClass:[GetMessageFromWXReq class]])
    {
        // 微信请求App提供内容， 需要app提供内容后使用sendRsp返回
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App提供内容"];
        NSString *strMsg = @"微信请求App提供内容，App要调用sendResp:GetMessageFromWXResp返回给微信";
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        alert.tag = 1000;
        [alert show];
    }
    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
    {
        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
        WXMediaMessage *msg = temp.message;
        
        //显示微信传过来的内容
        WXAppExtendObject *obj = msg.mediaObject;
        
        NSString *strTitle = [NSString stringWithFormat:@"微信请求App显示内容"];
        NSString *strMsg = [NSString stringWithFormat:@"标题：%@ \n内容：%@ \n附带信息：%@ \n缩略图:%lu bytes\n\n", msg.title, msg.description, obj.extInfo, msg.thumbData.length];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
    else if([req isKindOfClass:[LaunchFromWXReq class]])
    {
        //从微信启动App
        NSString *strTitle = [NSString stringWithFormat:@"从微信启动"];
        NSString *strMsg = @"这是从微信启动的消息";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}

-(void) onResp:(BaseResp*)resp
{
    if ([resp isKindOfClass:[SendAuthResp class]])
    {
        SendAuthResp *auth = (SendAuthResp *)resp;
        
        NSString *code = auth.code;
        
        [self getAccessToken:code];
    }
    
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        NSString *strTitle;
        if (_scene==0) {
            strTitle=@"分享好友";
        }
        if (_scene==1) {
            strTitle=@"分享朋友圈";
        }
        NSString *strMsgs;
        switch (resp.errCode) {
            case 0:
                strMsgs=@"发送成功";
                break;
            case -1:
                strMsgs=@"普通错误类型";
                break;
            case -2:
                strMsgs=nil;
                break;
            case -3:
                strMsgs=@"取消发送";
                break;
            case -4:
                strMsgs=@"授权失败";
                break;
            case -5:
                strMsgs=@"微信不支持";
                break;
                
            default:
                break;
        }
        if (strMsgs) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsgs delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
    
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle;
    
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
    }
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付结果：成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                break;
        }
    }
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

@end
